package com.example.j202411.viewmodel;

import android.content.Context;
import android.util.Log;


import com.example.j202411.contract.BooksContact;
import com.example.j202411.Model.Books;
import com.example.j202411.service.BooksService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

    public class BooksModel implements BooksContact.BooksPresenter{
        private static final String TAG = "BookPresenter";
        private static final String BASE_URL = "https://apis.juhe.cn/";
        private static final String API_KEY = "02759a01e0ccbeaae0526556634db600";
        private static final int API_PN = 1 ;
        private static final int API_RN = 30 ;
        private static final String API_DTYPE = "json" ;
        private BooksContact.BooksView view ;
        private Context context ;

        public BooksModel(BooksContact.BooksView view, Context context) {
            this.view = view;
            this.context = context;
        }

        @Override
        public void getData(int dtype) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build() ;

            BooksService service = retrofit.create(BooksService.class);
            service.getData(API_KEY,dtype,API_PN,API_RN,API_DTYPE)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new Observer<Books>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull Books books) {
                            if (books != null){
                                view.showData(books);
                            }else {
                                Log.e("空指针警告", "mMainView 为 null" );
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Log.e("错误处理", "数据获取失败: " + e.getMessage());
                        }

                        @Override
                        public void onComplete() {
                        }
                    }) ;
        }
    }
